package com.yeskery.nut.websocket;

import java.util.List;
import java.util.Map;

/**
 * 基础WebSocket会话对象
 * @author sprout
 * @version 1.0
 * 2023-04-22 14:12
 */
public abstract class BaseSession implements Session {

    /** 连接符 */
    private static final char AND_CHAR = '&';

    /** 请求路径 */
    private final String path;

    /** 请求参数 */
    private final Map<String, List<String>> params;

    /** 请求参数字符串 */
    private String queryString;

    /**
     * 构建基础WebSocket会话接口
     * @param path 请求路径
     * @param params 请求参数
     */
    public BaseSession(String path, Map<String, List<String>> params) {
        this.path = path;
        this.params = params;
    }

    @Override
    public String getRequestPath() {
        return path;
    }

    @Override
    public Map<String, List<String>> getRequestParameterMap() {
        return params;
    }

    @Override
    public String getQueryString() {
        if (queryString != null) {
            return queryString;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            for (String value : entry.getValue()) {
                stringBuilder.append(entry.getKey()).append("=").append(value).append("&");
            }
        }
        if (stringBuilder.length() <= 0) {
            return stringBuilder.toString();
        }
        if (stringBuilder.charAt(stringBuilder.length() - 1) == AND_CHAR) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        queryString = stringBuilder.toString();
        return queryString;
    }
}
